<template>
  <div class="login">
    <van-nav-bar title="用户登录" />
    <van-form
      class="form-box"
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-cell-group>
        <van-field
          :rules="[{ pattern: /^1\d{10}$/, message: '请输入正确手机号码' }]"
          v-model.trim="user.mobile"
          type="tel"
          label="手机号"
        />
        <van-field
          :rules="[{ pattern: /^\d{6}$/, message: '请输入正确格式密码' }]"
          v-model.trim="user.code"
          type="password"
          label="密码"
        />
      </van-cell-group>
      <div class="btnbox">
        <van-button type="info">登录</van-button>
      </div>
    </van-form>
    <!-- <van-button @click="hGetUserInfo" type="info">获取用户信息</van-button> -->
  </div>
</template>
<script>
import { login, getUserInfo } from '../../api/user.js'
export default {
  data () {
    return {
      user: {
        mobile: '13912345678',
        code: '246810'
      }
    }
  },
  methods: {
    onFailed () {
      console.log('验证失败')
    },
    onSubmit () {
      console.log('验证成功')
      this.hLogin()
    },
    async hLogin () {
      try {
        this.$toast.loading({
          duration: 0,
          overlay: true,
          message: '加载中...'
          //   forbidClick: true
        })
        const res = await login(this.user.mobile, this.user.code)
        console.log('res', res)
        this.$toast.success('欢迎用户' + this.user.mobile)
        this.$store.commit('mSaveToken', res.data.data)
        const userInfo = await getUserInfo()
        console.log('user', userInfo)
        this.$store.commit('mSaveUserInfo', userInfo)
        this.$router.push(this.$route.query.originpath || '/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败')
      }
    }
    // async hGetUserInfo () {
    //   try {
    //     const res = await getUserInfo()
    //     console.log('tres', res)
    //   } catch (err) {
    //     console.log(err)
    //   }
    // }
  }
}
</script>
<style lang="less" scoped>
.login .btnbox {
  padding: 0 20px; // 左右空20px
  button {
    width: 100%;
    background-color: #6db4fd;
    color: #fff;
  }
}
// .form-box {
//   margin-top: 30px;
// }
</style>
